﻿using B.S.BaseData.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BaseData.Infrastructure.Implement
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly DBContext db;

        public BaseRepository(DBContext db)
        {
            this.db = db;
        }
        public int Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }

        public Task<int> AddAsync(T entity)
        {
            db.Set<T>().AddAsync(entity);
            return db.SaveChangesAsync();
        }

      

        public int Del(T entity)
        {
           db.Set<T>().Remove(entity);
            return db.SaveChanges();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> predicate)
        {
            return await db.Set<T>().Where(predicate).ToListAsync();
        }

        public IQueryable<T> GetAll()
        {
           return db.Set<T>().AsQueryable();
        }

        public async Task<List<T>> GetAllAsync()
        {
           return await  db.Set<T>().ToListAsync();
        }

        public int Update(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChanges();
        }

        public Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChangesAsync();
        
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }


        /// <summary>
        /// 批量真删
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> DeleteRemove(List<T> entity)
        {
            db.Set<T>().RemoveRange(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        ///批量添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> AddRanges(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return db.SaveChanges();
        }
    }
}
